# -*- coding:utf-8 -*-
import requests
import json
import fitz  # PyMuPDF
import os
from llm_model import llm_extract_resume
# API 端点
url = 'https://openapi.italent.cn'

# 发起登录请求
def TokenAccess(url):
    # API Key 和 Secret
    api_key = 'C8D208DA1A474D0396AD324A9E5BE288'
    api_secret = 'ECE597E884EE4755B71EE33F14150C7D83B7D1A4ADA749BF81932998F435EBA4'
    # 构建请求内容
    token_body = {
        "grant_type": "client_credentials",
        "app_key": api_key,
        "app_secret": api_secret
    }
    # refresh_headers={
    #     "grant_type":"refresh_token",
    #     "refresh_token":"Z0HaROZY-q53LIdhb3y94tswmwBATOWqkjiz-2A4jTm7fnB4ly7A9UX9Pq3CV-yCMHC4Npgot"
    # }
    response = requests.post(url=url+'/token',data=token_body)
    if response.status_code == 200:
        # 解析响应内容
        token_json = response.json()
        access_token = token_json['access_token']
        print('Access Token:', access_token)
        return access_token
    else:
        print("Token Error")
        print(f"Error: {response.status_code}, {response.text}")
        return None

#获取一段时间内的初筛通过的申请人列表
def GetApplicantList(url,startTime,endTime, access_token):
    # 构建请求头
    api_headers = {
        'Authorization': f'Bearer {access_token}'
    }
    # 请求参数（如果需要）
    params = {
        "startTime": startTime,
        "endTime": endTime,
        "phaseCode": "S001",
        "statusCode": "U003"
    }
    api_response = requests.post(url=url + '/RecruitV6/api/v1/Apply/GetApplysByPhaseStatusCode', headers=api_headers, json=params)
    if api_response.status_code == 200:
        data = api_response.json()
        # print("Applicant list:",data)
        return data["data"]
    else:
        print("Applicant List Error")
        print(f"Error: {api_response.status_code}, {api_response.text}")
        return None

#根据申请id获取简历并解析成文字
def ResumeExtraction(url, access_token,applyid):
    # 构建请求头
    api_headers = {
        'Authorization': f'Bearer {access_token}'
    }
    api_url = url + '/RecruitV6/api/v1/Applicant/GetStandardResumeFileUrlByApplyId?applyId='+str(applyid)
    r = requests.get(url=api_url, headers=api_headers)
    data = r.json()
    #文件pdfurl获取
    fileurl = data["data"]['downloadUrl']
    response = requests.get(url='https:' + fileurl)
    pdf_filename = 'downloaded_file.pdf'
    with open(pdf_filename, 'wb') as file:
        file.write(response.content)
    print(f"PDF 文件已保存为 {pdf_filename}")
    pdf_document = fitz.open(pdf_filename)

    # 初始化一个字符串存储所有页面的文字
    text = ""

    # 遍历每一页并提取文字
    for page_num in range(len(pdf_document)):
        page = pdf_document.load_page(page_num)
        text += page.get_text()

    # 关闭 PDF 文件
    pdf_document.close()

    print("提取文字内容成功")
    return text

def ConstructPrompt(url, access_token,applicant):
    headers = {
        'Authorization': f'Bearer {access_token}'
    }
    JD_Title = applicant["jobLite"]["jobTitle"]
    JD_Guid = applicant["jobLite"]["jobGuid"]
    params = {
        "jobIds": [JD_Guid]
    }
    response = requests.post(url=url+"/RecruitV6/api/v1/Job/GetJobListByIds",json=params,headers=headers)
    Job = response.json()
    duty = Job['data'][0]['duty']
    requirements = Job['data'][0]['require']
    text = ResumeExtraction(url,token,applicant["applyId"])
    JDPrompt = """你是一个具有30年招聘工作经历的资深招聘专家，具有寿险公司前中后台各业务线招聘交付经验，
        擅长通过阅读简历为企业挑选合适的候选人。希望您做简历内容的提取并针对公司的岗位职责进行匹配、通过匹配度进行评价并打分。
        你需要了解的背景信息如下：我所在的公司是一家养老保险公司。公司的用人导向是年轻（40岁以下）、教育背
        景良好（本科211、985以上或是研究生以上），工作经历避免频繁跳槽。当前的岗位职责是""" + duty
    prompt = """,并根据提供的简历模板提取简历内容，输出为json，json格式为
        '''{
            "应聘岗位" : "",
            "姓名" : "",
            "年龄" : "",
            "工作年限" : "",
            "雇主名称" : ["雇主1","雇主2"],
            "最高学历",
            "最高学历毕业院校", 
            "最高学历专业",
            "所有教育信息" : [{"学校名称" : "专业" : ""},{"学校名称" : "专业" : ""}],
            "潜在风险" : "",
            "具体匹配项" : {
                "教育学历与专业" : {
                    "评分" : "",
                    "评分理由" : ""
                },
                "工作经历与项目经验" : {
                    "评分" : "",
                    "评分理由" : ""
                },
                "专业技能" : {
                    "评分" : "",
                    "评分理由" : ""
                },
                "组织管理能力" : {
                    "评分" : "",
                    "评分理由" : ""
                },
                "其他（软素质）" : {
                    "评分" : "",
                    "评分理由" : ""
                }
            },
            "总评分" : "",
            "总评分理由" : ""
        }'''" 应聘岗位、姓名到项目经验等基本信息要根据简历实际内容输出，不得揣测，年龄、最高学历就读时长的值必须是数字。提取出来的工作年限需要转换为数字。总结项目经验，要在150字左右。潜在风险等扩展能力需要根据简历扩展补充，不能为空，不得超过200字，
        最后需要根据岗位的五个维度要求进行匹配打分：具体包含（教育学历与专业、工作经历与项目经验、专业技能、组织管理能力、其他（软素质）这五个维度），每项20分。评分需要客观公正，如简历未提及某项，则打0分。最后各项评分累加形成总评分并综合给出总评分理由，要详细清晰。除了上述提及的json输出，不需要其他输出，不需加任何注释，完全按照上面给定的json格式输出。简历如下："""
    prompt = JDPrompt + prompt
    return prompt,text

def UpdateField(url, access_token, applicant,score,reason,risk):
    headers = {
        'Authorization': f'Bearer {access_token}'
    }
    applyid = applicant["applyId"]
    param = {
        "applyList": [
            {
                "applyId": applyid,
                "fieldValues": {
                    "extaipingfen_432693_1029075836": score,
                    "extpingfenliyou_432693_1234838049":reason,
                    "extfengxiantishi_432693_2119307952":risk
                }
            }],
        "isSkipApplyLock": False,
        "isSkipApplicantLock": True
    }
    update_response = requests.post(url=url+"/RecruitV6/api/v1/Apply/UpdateApplyList",json=param,headers=headers)
    if update_response.status_code == 200:
        print("更新成功")
    else:
        print("更新失败，errcode：", update_response.status_code, update_response.text)


token = TokenAccess(url)
startTime = "2024-07-03T23:59:59"
endTime = "2024-08-16T23:59:59"
data = GetApplicantList(url, startTime, endTime, token)
applicants = data['items']

for applicant in applicants:
    prompt,text = ConstructPrompt(url,token,applicant)
    try:
        response_json = llm_extract_resume("wenxin", prompt, text)
    except Exception as e:
        response_json = None
        print("调用大模型失败", e)

    score = response_json['总评分']
    reason = response_json['总评分理由']
    risk = response_json['潜在风险']

    UpdateField(url,token,applicant,score,reason,risk)
    # ai评分：extaipingfen_432693_1029075836
    # 评分理由：extpingfenliyou_432693_1234838049
    # 风险提示：extfengxiantishi_432693_2119307952
    name = applicant['applicantLite']['name']
    print(name,"简历评分完成")

